package com.cater.utils;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.alibaba.fastjson.JSONObject;
import com.cater.sys.entity.Filestorage;
import com.cater.sys.service.FilestorageService;

public class JsonUtil {
	
	/**
	 * 实现自定义字段解析
	 * @param params
	 * @param request
	 * @param filestorageServiceImpl
	 * @return
	 */
	public static String jspJsontoString(Map<String, String[]> params,HttpServletRequest request,FilestorageService filestorageServiceImpl) {
		JSONObject json = new JSONObject();
		for (String key : params.keySet()) {
			JSONObject jsons = new JSONObject();
            String[] values = params.get(key); 
            String typevalue = "";
            if(values.length>2){//确定是新增列
            	 for (int i = 0; i < values.length; i++) {  
                     String value = values[i];
                     if(i==0){
                     	 jsons.put(key, value);
                     }else if(i==1){
                    	 if(value.equals("0")){
                    		 jsons.put("id", UUID.randomUUID().toString().replaceAll("-", ""));
                    	 }else{
                    		 jsons.put("id", value);
                    	 }
                     }else if(i==2){
                     	jsons.put("inputtype", value);
                     	typevalue =value;
                     	if(value.equals("icon-picture") || value.equals("icon-folder-close-alt")){
                     		CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
                                    request.getSession().getServletContext());
                         	 if(multipartResolver.isMultipart(request))
                             {
                                 //将request变成多部分request
                                 MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
                               //一次遍历所有文件
                                 MultipartFile files=multiRequest.getFile(key);
                                 if(files!=null){
                                	 String realPath=request.getSession().getServletContext().getRealPath("/")+"static/upload/";
                                	 List<Filestorage> list = filestorageServiceImpl.getAllByattributeId(jsons.getString("id"),key);
                                	 if(list!=null && list.size()>0){
                                		 Filestorage filestorage = filestorageServiceImpl.getById(list.get(0).getFlieId()+"");
 	                             	    File file = new File(realPath+filestorage.getFlieName());
 	                             	    if(file.exists()){
 	                             	    	file.delete();
 	                             	    }
 	                             	   filestorageServiceImpl.delete(filestorage.getFlieId());
                                	 }
                                	 UploadUtil.fileUploads(null, files,jsons.getString("id"), key,1, request, filestorageServiceImpl);
                                 }
                             }
                     	}
                     }else if(i==3){
                     	jsons.put("iseye", value);
                     }else if(i==4){
                    	 jsons.put("sort", value);
                     }else if(i==5){
                    	 if(typevalue.equals("icon-time")){
                    		 System.out.println(value);
                    		 if(value.equals("系统自动填充")){
                    			 jsons.put("value", StringUitl.getDate()); 
                    		 }else{
                    			 jsons.put("value", value); 
                    		 }
                    	 }else if(typevalue.equals("icon-user")){
                    		 jsons.put("value", StringUitl.getUser(request).getTruename()); 
                    	 }else{
                    		 jsons.put("value", value); 
                    	 }
                     }
                 }
            	 json.put(key, jsons);
            }
        }
		 
		return json.toString();
	}
	
	
	public static String templateJsonToString(Map<String, String[]> params) {
		JSONObject json = new JSONObject();
		for (String key : params.keySet()) {
			JSONObject jsons = new JSONObject();
			String[] values = params.get(key);
			if (values.length != 1) {// 确定是新增列
				for (int i = 0; i < values.length; i++) {
					String value = values[i];
					if (i == 0) {
						jsons.put(key, value);
					} else if (i == 2) {
						jsons.put("iseye", value);
					} else if (i == 1) {
						jsons.put("inputtype", value);
					}else if(i==3){
                    	 jsons.put("sort", value);
                     }
				}
				json.put(key, jsons);
			}
		}
		return json.toString();
	}
	
	
	public static  List<Map<String, Object>> stringJsontoMap(String stringJson){
		 List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
		try {
			JSONObject json =JSONObject.parseObject(stringJson);
			Set<String> keys=json.keySet();
			for (String string : keys) {
				Map<String, Object> map = new HashMap<String, Object>();
				 JSONObject jsons =JSONObject.parseObject(json.getString(string));
					Set<String> keyss=jsons.keySet();
					for (String string2 : keyss) {
						 map.put(string2, jsons.getString(string2));
					}
				list.add(map);
			}
		} catch (Exception e) {
			System.out.println("json数据格式错误");
		}
		return list;
	}
	
	public static  String ListMapToJsonString(List<Map<String, Object>> list){
		JSONObject json = new JSONObject();
		for (Map<String, Object> map : list) {
			JSONObject jsons = new JSONObject();
			for (String string : map.keySet()){
				jsons.put(string, map.get(string));
			}
			json.put((String) map.get("id"), jsons);
		}
		return json.toString();
	}
	
	
	/**
	 * 检测报告生产节点详细自定义字段
	 * @param params
	 * @param request
	 * @param filestorageServiceImpl
	 * @return
	 */
	public static String jiancbgtoString(Map<String, String[]> params, String imgurl, HttpServletRequest request,
			FilestorageService filestorageServiceImpl) {
		JSONObject json = new JSONObject();
		for (String key : params.keySet()) {
			JSONObject jsons = new JSONObject();
			String[] values = params.get(key);
			String typevalue = "";
			if (values.length > 2) {// 确定是新增列
				for (int i = 0; i < values.length; i++) {
					String value = values[i];
					if (i == 0) {
						jsons.put(key, value);
					} else if (i == 1) {
						if (value.equals("0")) {
							jsons.put("id", UUID.randomUUID().toString().replaceAll("-", ""));
						} else {
							jsons.put("id", value);
						}
					} else if (i == 2) {
						jsons.put("inputtype", value);
						typevalue = value;
						if (value.equals("icon-picture") || value.equals("icon-folder-close-alt")) {
							Filestorage storage = new Filestorage();
							storage.setFlieName(imgurl.split("static/upload/")[1]);
							storage.setAttributeId(jsons.getString("id"));
							storage.setAttributetype(key);
							storage.setFlieSize(1.2);
							storage.setFlieType(".jpg");
							storage.setType(1);
							filestorageServiceImpl.save(storage);
					}} else if (i == 3) {
						jsons.put("iseye", value);
					} else if (i == 4) {
						jsons.put("sort", value);
					} else if (i == 5) {
						if (typevalue.equals("icon-time")) {
							System.out.println(value);
							if (value.equals("系统自动填充")) {
								jsons.put("value", StringUitl.getDate());
							} else {
								jsons.put("value", value);
							}
						} else if (typevalue.equals("icon-user")) {
							jsons.put("value", StringUitl.getUser(request).getTruename());
						} else {
							jsons.put("value", value);
						}
					}
					json.put(key, jsons);
				}
			}
		}
		return json.toString();
	}
}
